import axios from 'axios'
import {message} from 'antd';
import qs from 'qs';
// 创建axios实例
const service = axios.create({
  baseURL: "/oss", // api的base_url
  timeout: 15000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  config.url += `${config.url.indexOf('?') > 0 ? '&' : '?'}cb=${new Date().getTime()}`;
  if(config.headers !== "undefined") {
    if(config.headers['Content-Type'] === ""||config.headers['Content-Type'] === undefined){
      config.headers['Content-Type'] = "application/json;charset=UTF-8"
    }
  }
  config.withCredentials = true;
  return config
})

// respone拦截器
service.interceptors.response.use(
  response => {
  /**
  * code为非20000是抛错 可结合自己业务进行修改
  */
    const res = response.data
    if(res.code == null){
      return response.data
    }
    if (res.code !== 200) {
      message.error(res.message,5)
      return response.data
    } else {
      return response.data
    }
  },
  error => {
        /**
     * 处理token过期
     */
   let headers = error.response.headers;
   if(headers.loginstatus !=="undefined"&& headers.loginstatus ==="expired" && error.response.status === 401){
     message.warning('您的登录已过期，请重新登录')
     localStorage.removeItem("ossToken")
     return error.response.status
   }
   if(error.response.status === 401){
    message.error("无权访问",5)
    return error.response.status
   }
    console.log('err' + error)// for debug
    message.error(error.message,5)
    return error.response.status
     //return Promise.reject(error.response)
  }
)
export default service
